# 百度翻译方法
# def baidu_translate(content):
#     # print(content)
#     if len(content) > 4891:
#         return '输入请不要超过4891个字符！'
#     salt = str(random.randint(0, 50))
#     # 申请网站 http://api.fanyi.baidu.com/api/trans
#     appid = '20231020001853827'  # 这里写你自己申请的
#     secretKey = 'vpjD5ti_efOUikC3ax2p'  # 这里写你自己申请的
#     sign = appid + content + salt + secretKey
#     sign = hashlib.md5(sign.encode(encoding='UTF-8')).hexdigest()
#     head = {'q': f'{content}',
#             'from': 'en',
#             'to': 'ch',
#             'appid': f'{appid}',
#             'salt': f'{salt}',
#             'sign': f'{sign}'}
#     j = requests.get('http://api.fanyi.baidu.com/api/trans/vip/translate', head)
#     # print(j.json())
#     res = j.json()['trans_result'][0]['dst']
#     res = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]').sub(' ', res)
#     # print(res)
#     return res
#
#
# ret = baidu_translate("hello")
# print(ret)


import json
import random
from hashlib import md5

import requests

str ="   "
str = str.strip()

print(not str)
# Set your own appid/appkey.
appid = '20231020001853827'
appkey = 'vpjD5ti_efOUikC3ax2p'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang = 'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

query = ''


# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)

# Build request
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

# Send request
r = requests.post(url, params=payload, headers=headers)
result = r.json()
print(result)
if result['error_code']:
    print(result['error_msg'])
else:
    print(result["trans_result"][0]["dst"])
# print(json.dumps(result,indent=4,ensure_ascii=False)["trans_result"])
# Show response
# print(json.dumps(result, indent=4, ensure_ascii=False))
